package com.sxds.wn.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.sxds.wn.IConstants;
import com.sxds.wn.service.IService;
import com.sxds.wn.service.Request;
import com.sxds.wn.service.Response;

/**
 * Description: <p>系统Servlet抽象类</p>
 * Content Desc:<p>系统Servlet抽象类,提取公共方法，做抽象接口供下级使用<p>
 * Copy Right of Personal Tangtao 2007-2020
 * @author Andy
 * @version 1.0 Create Date:@2008-12-12
 */
public abstract class BaseServlet extends HttpServlet implements IConstants{

	/**系列表示号**/
	private static final long serialVersionUID = 292932L;
	/**日志记录**/
	protected Log log = LogFactory.getLog(getClass());
	/**Spring IOC 容器**/
	private ApplicationContext applicationContext;
	
	/**
	 * 默认构造方法
	 */
	public BaseServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		this.applicationContext = null;
		super.destroy(); 
	}
	
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		this.applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
	}
	
	/**
	 * 供下级继承类使用
	 * @return
	 */
	protected ApplicationContext getApplicationContext(){
		return this.applicationContext;
	}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String serviceBean = request.getParameter("serviceBean");
		IService service = (IService)this.applicationContext.getBean(serviceBean);
		//处理类型,1--处理返回tree对象，2--处理返回json的分页格式
		String processType = request.getParameter("processType");
		//默认处理是返回json tree格式对象
		if( processType==null || "".equals(processType) ) processType = "1";
		Request andyRequst = new Request(request);
		Response andyResponse = null;
		try{
			andyResponse = service.process(andyRequst);
			//处理返回结果,下级
			processResponse(request, response, andyRequst, andyResponse);
		}catch(Exception ex){
			log.error("处理请求错误：",ex);
			this.processExceptionWithNomal(request, response, ex, andyResponse);
		}
	}
	
	/**
	 * 用正常方式处理异常，直接返回到页面上
	 * @param request
	 * @param response
	 * @param ex
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void processExceptionWithNomal(HttpServletRequest request, HttpServletResponse response,Exception ex,Response andyResponse) throws ServletException, IOException {
		request.setAttribute("exception", ex);
		throw new ServletException("请求错误:"+ex);
	}
	
	/**
	 * 使用Json方式处理异常，封装成
	 * @param request
	 * @param response
	 * @param ex
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void processExceptionWithJson(HttpServletRequest request, HttpServletResponse response,Exception ex,Response andyResponse) throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding(request.getCharacterEncoding());
		JSONObject jsonObject = new JSONObject();
		jsonObject.put(EXT_SUCCESS_KEY, andyResponse.isOk());
		jsonObject.put(EXT_MESSAGE_KEY,andyResponse.getResponseMessage());
		jsonObject.put(EXT_RESPONSE_CODE_KEY,andyResponse.getResponseCode());
		jsonObject.put(EXT_EXCEPTION, ExceptionUtils.getStackTrace(ex));
		PrintWriter out = response.getWriter();
		jsonObject.write(out);
		out.flush();
		out.close();
	}
	
	/**
	 * 处理返回结果，下级必须实现处理
	 * @param request HttpServletRequest
	 * @param response HttpServletResponse
	 * @param andyRequst Request
	 * @param andyResponse Response
	 * @throws ServletException Servlet异常
	 * @throws IOException IO异常
	 */
	protected abstract void processResponse(HttpServletRequest request,
			HttpServletResponse response, Request andyRequst,
			Response andyResponse) throws ServletException, IOException;
		
}
